package com.kafka.kafka.study;

import com.kafka.kafka.utils.PropertiesUtils;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;

import java.util.Properties;

/**
 * Project: tobe-better-coder
 * Package: com.kafka.kafka.study
 *
 * @author : Mr.xu
 * @date : 2023/9/10 14:53
 */
public class CustomProducerTransaction {

    public static void main(String[] args) {
        //1.创建配置
        Properties properties = PropertiesUtils.getKafkaProperties("node1:9092,node2:9092");

        //指定事务id
        properties.put(ProducerConfig.TRANSACTIONAL_ID_CONFIG,"transaction_id_001");

        //创建kafka生产者对象
        KafkaProducer<String, String> kafkaProducer = new KafkaProducer<>(properties);

        //初始化事务
        kafkaProducer.initTransactions();
        //开始事务
        kafkaProducer.beginTransaction();
        try {
            for (int i = 0; i < 5; i++) {
                //发送消息
                kafkaProducer.send(new ProducerRecord<>("kafka", "hello kafka" + i));
            }
            //提交事务
            kafkaProducer.commitTransaction();
        } catch (Exception e) {
            //终止事务
            kafkaProducer.abortTransaction();
        } finally {
            kafkaProducer.close();
        }

    }
}